﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Linq.Expressions;

namespace FanPages.Common.DataAccess
{
    public class EFRepository<Entity> : IRepository<Entity> where Entity : class
    {

        IObjectSet<Entity> objectSet;
        
        public ObjectContext Context { get; set; }

        public EFRepository(ObjectContext context)
        {
            Context = context;
            objectSet = context.CreateObjectSet<Entity>();
        }

        public IQueryable<Entity> AsQueryable()
        {
            return objectSet;
        }

        public IEnumerable<Entity> Find(Expression<Func<Entity, bool>> where)
        {
            return objectSet.Where(where);
        }

        public IEnumerable<Entity> GetAll()
        {
            return objectSet.ToList();
        }

        public Entity Single(Expression<Func<Entity, bool>> where)
        {
            return objectSet.Single(where);
        }

        public Entity First(Expression<Func<Entity, bool>> where)
        {
            return objectSet.FirstOrDefault(where);
        }

        public void Delete(Entity entity)
        {
            objectSet.DeleteObject(entity);
            Context.SaveChanges();
        }

        public void Add(Entity entity)
        {
            objectSet.AddObject(entity);            
            Context.SaveChanges();
        }

        public void Attach(Entity entity)
        {            
            objectSet.Attach(entity);
            Context.SaveChanges();
        }


        public void Update(Entity entity)
        {                        
            Context.SaveChanges();
            
        }
    }
}
